﻿using Kxx_Common;
using Kxx_Common.INI;
using Kxx_Common.Tools;
using Kxx_Log.Log;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Documents;

namespace Handy_DNS.Load
{
    internal class LogSocket
    {
        private static Socket tcpSocket;

        #region 初始化
        /// <summary>
        /// 初始化
        /// </summary>
        public static void Init()
        {
            MonitorTask();

            LogTask();
        }
        #endregion

        #region 任务
        /// <summary>
        /// 通讯监控任务（5秒刷新）
        /// </summary>
        private static void MonitorTask()
        {
            new Task(() =>
            {
                while (true)
                {
                    if (tcpSocket == null || !tcpSocket.Connected)
                    {
                        try
                        {
                            INIFile ini = new INIFile(AppDomain.CurrentDomain.BaseDirectory + @"bascconfig.ini");
                            int port = ini.IniReadValue("DNS", "SPort").ToInt();

                            IPAddress iP = IPAddress.Parse("127.0.0.1");
                            IPEndPoint iPEndPoint = new IPEndPoint(iP, port);
                            tcpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                            tcpSocket.Connect(iPEndPoint);

                            DNSLog.LogAdd(LogType.Success, "服务通讯", $"连接成功");
                        }
                        catch
                        {
                            DNSLog.LogAdd(LogType.Error, "服务通讯", $"连接失败");
                        }
                    }

                    Thread.Sleep(5000);
                }
            }).Start();
        }

        /// <summary>
        /// 日志任务（5秒刷新）
        /// </summary>
        private static void LogTask()
        {
            new Task(() => {
                byte[] data = new byte[1024 * 1024];
                while (true)
                {
                    try
                    {
                        if (tcpSocket != null && tcpSocket.Connected)
                        {
                            int receiveLen = tcpSocket.Receive(data);

                            List<LogModel> logList = ConvertJson.DeserializeJsonToList<LogModel>(Encoding.UTF8.GetString(data, 0, receiveLen));

                            foreach (LogModel model in logList)
                            {
                                DNSLog.LogList.Add(model);
                            }
                        }
                    }
                    catch { }

                    Thread.Sleep(5000);
                }
            }).Start();
        }
        #endregion
    }
}
